<template>
  <div>
    <div class="flex-box mb-10">
      <div v-if="!!flag" class="flex-box-left">
        <el-form
          ref="form"
          :model="searchForm"
          label-width="180px"
          inline
        >
          <el-form-item label="单项工程编码：" style="width: 400px">
            <el-input v-model="searchForm.inputValue" />
          </el-form-item>
          <el-button
            class="pms-button-primary mt-10 ml-10"
            @click="handleSearch"
          >筛选</el-button>
        </el-form>
        <div class="tip-info">例如输入"单项工程编码"后点击按钮</div>
      </div>

      <div
        v-if="(!sjbgcheck && reState) && acceptcheck"
        class="flex-box-right"
        :class="{ 'position-abs': !flag, 'abs-right': !flag }"
      >
        <span>计划领用时间</span>
        <el-date-picker
          v-model="planGetTime"
          type="date"
          placeholder="选择日期"
          :disabled="!isEdit || !metaEdit"
          class="pms-el-datepicker"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
        />
        <el-button
          v-if="isEdit && metaEdit"
          v-debounce="() => handleAllClick('all')"
          class="pms-button-primary mb-5"
          :disabled="btnAllState || !isEdit || !metaEdit"
        >全部领用</el-button>
        <el-button
          v-if="isEdit && metaEdit"
          v-debounce="handleAllClick"
          class="pms-button-primary mb-5"
          :disabled="btnState || !isEdit || !metaEdit"
        >确认领用</el-button>
        <el-button
          v-if="isEdit && metaEdit && checkAdjustButton"
          v-debounce="adjustProject"
          class="pms-button-primary mb-5"
        >跨项目调整</el-button>
      </div>
    </div>
    <div
      v-if="(!sjbgcheck && reState) && acceptcheck"
      class="mt-10 materials-remark-wrapper mb-10"
    >
      <span>请选择领料方式：</span>
      <el-select
        v-model="selectValue"
        placeholder="请选择"
        class="mb-10"
        size="mini"
        :disabled="!isEdit || !metaEdit"
        @change="handleChange"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <div class="materials-remark-wrapper-title">物资申领备注</div>
      <el-input
        v-model="materialsRemarks"
        type="textarea"
        :rows="2"
        :disabled="!isEdit || !metaEdit"
        placeholder="请输入物资申领备注"
      />
    </div>
    <wz-table
      :columns="wzApplicationColumn"
      :use-index="true"
      :table-data="designData"
    >
      <!-- 设计数量 -->
      <!-- 累计申领数量 -->
      <template #header="{ col }">
        <div v-if="col.details">
          <el-tooltip
            class="item"
            effect="dark"
            :content="col.details"
            placement="top-start"
          >
            <span> {{ col.label }}</span>
          </el-tooltip>
        </div>
        <div v-else>
          {{ col.label }}
        </div>
      </template>

      <!-- 源头赋码标识 -->
      <template #ifSourceCode="{ row }">
        <div>
          {{ +row.ifSourceCode ? "否" : "是" }}
        </div>
      </template>
      <!-- 本次申领数量 -->
      <template #receiveAmount="{ row }">
        <el-input
          v-model="row.receiveAmount"
          :disabled="nonarrivalDisabled(row) || !isEdit||!(!sjbgcheck && reState) || !metaEdit"
          class="pms-wz-input el-table-inline"
        />
      </template>
    </wz-table>
      <adjust-project-dialog v-if="showAdjustProject" :visible.sync="showAdjustProject" v-on="$listeners" :orgId="projectInfo.orgId"></adjust-project-dialog>
  </div>
</template>
<script>
// 整体项目物资申领表
import AdjustProjectDialog from "@/views/material/dialogComponents/adjustProjectDialog.vue";

const MATERIAL_APP_ALL_LIST = [
    {
        label: '单项工程编码',
        prop: 'prjcode',
        elProps: {
            width: '180px'
        }
    },
    {
        label: '站址编码',
        prop: 'siteId'
    },
    {
        label: '物料编码',
        prop: 'categorycode'
    },
    {
        label: '物料名称',
        prop: 'categoryname'
    },
    {
        label: '自定义规格',
        prop: 'dwjl'
    },
    {
        label: '计量单位',
        prop: 'unit'
    },
    {
        label: '主设备标识名称',
        prop: 'spuMainName',
        elProps: {
            width: '140px'
        }
    },
    {
        label: '源头赋码标识',
        prop: 'ifSourceName',
        elProps: {
            width: '180px'
        }
    },
    {
        label: '设计数量',
        prop: 'amount',
        elProps: {
            width: '80px'
        }
    },
    {
        label: '本次申领数量',
        prop: 'receiveAmount',
        elProps: {
            width: '140px'
        }
    }
]
// 系统常量配置
import wzTable from './cTable'
import {
    addApplyDetail,
    getEquipList,
    getSpuUnitAccByMaterialCode,
    addAllApplyDetail, checkNodeByPrjId
} from '@/api/material'
export default {
    name: 'MaterialsApplication',
    components: {AdjustProjectDialog, wzTable },
    props: {
        flag: {
            type: Number,
            default: 1
        },
        note: {
            type: String,
            default: ''
        },
        receiveDetailsData: {
            type: Object,
            default: () => {
                return {
                    overallDesignInfo: []
                }
            }
        },
        prjParams: {
            type: Object,
            default: () => ({})
        },
        metaEdit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            fileList: [],
            designData: [],
            materialRemovalVisible: false,
            materialBackVisible: false,
            arrivalVisible: false,
            planGetTime: '',
            wzApplicationColumn: [],
            nonarrivalNumForm: {
                nonarrivalNum: ''
            },
            materialsRemarks: '',
            projectInfo: {
                projectName: ''
            },
            searchForm: {
                inputValue: ''
            },
            selectValue: '',
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000
                }
            },
            optionsContents: {
                1: '物料自提，无需送货',
                2: '物料配置地址：',
                3: ''
            },
            optionsChangeTip: {
                1: '当前所选的领料方式为自提:无需送货',
                2: '当前所选的领料方式为配送，请根据实际情况调整备注信息中的收货地址！',
                3: '当前所选的领料方式为施工单位仓库，请根据实际情况在备注信息中填写施工单位仓库地址！'
            },
            options: [
                {
                    value: '1',
                    label: '自提'
                },
                {
                    value: '2',
                    label: '配送',
                    content: '物料配置地址：'
                },
                {
                    value: '3',
                    label: '施工单位仓库',
                    content: ''
                }
            ],
            currentValue: '',
            btnState: false,
            btnAllState: false,
            loading: false,
            showAdjustProject:false,
            checkAdjustButton:false
        }
    },
    computed: {
        query() {
            return this.$route.query
        },
        sjbgcheck() {
            if (this.receiveDetailsData.prjInfo) {
                return !!+this.receiveDetailsData.prjInfo.sjbgcheck
            }
            return false
        },
        reState() {
            if (this.receiveDetailsData.prjInfo) {
                return !+this.receiveDetailsData.prjInfo.reState
            }
            return false
        },
        acceptcheck() {
            if (this.receiveDetailsData.prjInfo) {
                return !+this.receiveDetailsData.prjInfo.acceptcheck
            }
            return true
        },
        isEdit() {
            if (this.receiveDetailsData.prjInfo) {
                return !!+this.receiveDetailsData.prjInfo.isEdit
            }
            return true
        }
    },
    watch: {
        receiveDetailsData: {
            handler(newValue) {
                this.projectInfo = newValue.prjInfo
            },
            deep: true,
            immediate: true
        },
        materialsRemarks: {
            handler(newValue) {
                this.$emit('update:note', newValue)
            }
        }
    },
    async created() {
        this.wzApplicationColumn = JSON.parse(
            JSON.stringify(MATERIAL_APP_ALL_LIST)
        )

        const res = await getEquipList({ prjId: this.prjParams.prjId })
        if (+res.code === 200) {
            this.designData = res.data
        }
    },
    mounted() {
        this.getCheckNodeByPrjId();
        console.log(this.projectInfo)
    },
    methods: {
        getCheckNodeByPrjId(){
            checkNodeByPrjId(this.query.prjId).then((res)=>{
                if(+res.code === 200){
                    this.checkAdjustButton = true;
                }
            })
        },
        adjustProject(){
            this.showAdjustProject=true;
        },
        nonarrivalDisabled(row) {
            if (+row.canReceive) {
                return false
            }
            return true
        },

        // 点击‘确定’按钮时

        // 点击出库数量
        handleMaterialsDetail() {
            this.materialRemovalVisible = true
        },
        // 退库数量
        handleMaterialBackVisible() {
            this.materialBackVisible = true
        },
        // 已贴标签数量
        handleArrivalVisible() {
            this.arrivalVisible = true
        },
        // 筛选
        async handleSearch() {
            const res = await getEquipList({
                prjId: this.query.prjId,
                key: this.searchForm.inputValue
            })
            if (+res.code === 200) {
                this.designData = res.data
            }
        },
        // 请选择领料方式
        handleChange(value) {
            console.log(this.optionsContents[value])
            this.materialsRemarks = this.optionsContents[value]
            this.$alert(this.optionsChangeTip[value], '提示', {
                confirmButtonText: '确定',
                type: 'warning'
            })
        },
        async handleAllClickrepairOne(){
            if (!this.materialsRemarks) {
                this.$message.warning('请您填写物资申领备注信息！')
                return Promise.reject()
            }
            if (!this.planGetTime) {
                this.$message.warning('请您填写计划领用时间！')
                return Promise.reject()
            }
        },
        async handleAllClickrepairTwo(addAllApplyDetailRes){
            if (+addAllApplyDetailRes.code === 200) {
                this.$message.success('提交成功')
                this.$emit('addApplyDetail')
            }
        },
        async handleAllClickrepairThree(applys){
            if (!applys.length) {
                this.$message.warning('请输入对应站址的申领物资数量！')
                return Promise.reject()
            }
        },
        async handleAllClickrepairFour(addApplyDetailRes){
            if (+addApplyDetailRes.code === 200) {
                this.$message.success('提交成功')
                this.loading.close()
                this.$emit('addApplyDetail')
            }
        },
        async handleAllClickrepairFive(getSpuUnitAccByMaterialCodeRes){
            if (+getSpuUnitAccByMaterialCodeRes.code !== 200) {
                return Promise.reject()
            }
        },
        async handleAllClickrepairSix(item){
            return item.receiveAmount || 1
        },
        async handleAllClickrepairSeven(){
            return this.projectInfo.siteName || ''
        },
        async handleAllClickrepairEight() {
            return !(
                this.query.manageMode === '03' ||
                this.query.manageMode === '04'
            )
                ? 1
                : ''
        },
        async handleAllClick(type) {
            await this.handleAllClickrepairOne()
            let applys = this.designData.map((item) => {
                return {
                    canReceive: item.canReceive,
                    ifSourcecode: item.ifSourceCode,
                    siteAddress: item.siteAddress,
                    siteId: item.siteId,
                    spuMainName: item.spuMainName,
                    amount: item.amount,
                    categoryCode: item.categorycode,
                    categoryName: item.categoryname,
                    dwjl: item.dwjl,
                    iftwodecimals: item.iftwodecimals,
                    oldPrice: item.oldprice,
                    prjCode: item.prjcode,
                    prjId: item.prjid,
                    subPrjId: item.subprjid,
                    unit: item.unit,
                    receiveAmount: item.receiveAmount
                }
            })
            const prjInfo = {
                adjId: '',
                applyType: this.selectValue,
                note: this.materialsRemarks,
                pagesize: 10,
                planTime: this.planGetTime,
                prjId: this.query.prjId
            }
            if (type === 'all') {
                this.btnAllState = true
                const timer = setTimeout(() => {
                    this.btnAllState = false
                    clearTimeout(timer)
                }, 5 * 1000)
                applys = applys.map((item) => {
                    return {
                        ...item,
                        receiveAmount: item.receiveAmount || 1
                    }
                })
                const addAllApplyDetailRes = await addAllApplyDetail({
                    prjInfo
                })
                await this.handleAllClickrepairTwo(addAllApplyDetailRes)
            } else {
                this.btnState = true
                const timer = setTimeout(() => {
                    this.btnState = false
                    clearTimeout(timer)
                }, 5 * 1000)
                applys = applys.filter((item) => {
                    return +item.receiveAmount > 0
                })
                await this.handleAllClickrepairThree(applys)
                applys = applys.map((item, index) => {
                    return {
                        ...item,
                        receiveAmount: item.receiveAmount
                    }
                })
                const params = {
                    applys,
                    prjInfo
                }
                for (const row of applys) {
                    const materialCheckParams = {
                        receiveAmount: row.receiveAmount,
                        materialCode: row.categoryCode,
                        amountType: 1, // 撤销领用
                        siteName:await this.handleAllClickrepairSeven(),
                        queryType:await this.handleAllClickrepairEight(),
                        note: this.note,
                        siteId: row.siteId
                    }
                    const getSpuUnitAccByMaterialCodeRes =
                        await getSpuUnitAccByMaterialCode(materialCheckParams)
                    await this.handleAllClickrepairFive(getSpuUnitAccByMaterialCodeRes)
                }
                this.loading = this.$loading({
                    lock: true,
                    text: '物资申领中,请稍后...',
                    spinner: 'el-icon-loading',
                    fullscreen: false
                })
                try {
                    const addApplyDetailRes = await addApplyDetail(params)
                    await this.handleAllClickrepairFour(addApplyDetailRes)
                } catch (error) {
                    this.loading.close()
                } finally {
                    this.loading.close()
                }
            }
        }
    }
}
</script>
<style scoped lang="scss">
.el-upload--text {
    width: 100%;
}
.btnflex {
    display: flex;
    justify-content: space-between;
}
.el-table th {
    padding: 0px 0;
    text-align: center;
    font-size: 12px;
    color: #333333;
    letter-spacing: 0;
}
.el-table td {
    padding: 0px 0;
    text-align: center;
    font-size: 2px;
    color: #333333;
    letter-spacing: 0;
}
.click-row {
    color: #53c7f8;
    cursor: pointer;
}
.materials-remark-wrapper {
    position: relative;
    border: 1px solid #ccc;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 20px;
    padding-bottom: 10px;
    &-title {
        position: absolute;
        left: 50%;
        top: -13px;
        background: #fff;
        font-weight: bold;
    }
}

.mt-10 {
    margin-top: 10px;
}
.mb-10 {
    margin-bottom: 10px;
}
.mb-5 {
    margin-bottom: 5px;
}
.ml-10 {
    margin-left: 10px;
}
.mr-10 {
    margin-right: 10px;
}
.tip-info {
    /*display: flex;*/
    /*height: 44px;*/
    /*margin-top: 14px;*/
    /*white-space: nowrap;*/
    margin-left: 10px;
    margin-right: 10px;
    min-width: 80px;
}
.flex-box {
    display: flex;
    width: 100%;
    align-items: center;
    height: auto;
    position: relative;
    &-left {
        display: flex;
        align-items: center;
        margin-right: auto;
    }
}
.pms-el-datepicker {
    margin-left: 10px;
    margin-right: 10px;
    height: 24px;
    ::v-deep .el-input__inner {
        height: 24px;
    }
    ::v-deep .el-input__icon {
        line-height: 20px;
    }
}
.position-abs {
    position: absolute;
}
.abs-right {
    right: 10px;
}
.pms-wz-input {
    ::v-deep .el-input__inner {
        background-color: #fffaee !important;
    }
    ::v-deep .el-input__inner:disabled {
        background-color: #f5f7fa !important;
    }
}

</style>
